import 'dart:convert';
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/config/config.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';
import 'package:shop/shop/life/AddDizhi.dart';
import 'package:shop/shop/life/DizhiGuanli.dart';
import 'package:shop/shop/life/PayMima.dart';
import 'package:shop/shop/life/ZitiListPage.dart';
class LjgmOrder extends StatefulWidget {
  String gid;//商品ID
  String adId;//地址ID
  String names;//规格
  String params;//规格下标
  double money;//选定规格金额
  int peisong;//配送类型
  int num;//数量
  double allMoney;//总金额
  String orRemark;//订单备注
  LjgmOrder({Key key, this.title, this.gid, this.adId, this.names, this.params, this.money,this.peisong,this.num,this.allMoney,this.orRemark}) : super(key: key);

  final String title;

  @override
  _LjgmOrder createState() => _LjgmOrder(gid,adId,names,params,money,peisong,num,allMoney,orRemark);
}

class _LjgmOrder extends State<LjgmOrder> {

  String adId;//收货地址ID
  String names;//规格
  String params;//规格下标
  int peisong=1;  //配送方式 默认快递1   自提0
  bool hasDefaultZiti=false;//是否有默认自提点
  var obj = {};// 查询的商品
  var num=1;  // 购买的个数
  var allMoney=0.00;  //商品金额总和
  double price = 0.00;//商品价格
  var yunfei = 0.00;//运费
  var userId="";//用户ID
  var orRemark="";//订单备注
  var address = {};//用户默认地址或选中的地址
  var zitiAddress = {};//用户默认自提点或选中的自提点
  int addressCode = 400;//判断是否有默认地址

  var _controller = TextEditingController();

  // 构造方法
  _LjgmOrder(gid,adId,names,params,money,peisong,num,allMoney,orRemark){
    this.adId = adId;
    this.names = names;
    this.params = params;
    this.orRemark = orRemark;
    if(allMoney!=null && allMoney!=""){
      this.allMoney = allMoney;
    }
    if(money!=null && money!=""){
      this.price = money;
    }
    if(num!=null && num!=""){
      this.num = num;
    }
    if(peisong!=null && peisong!=""){
      this.peisong = peisong;
    }
    _onLoading(gid,money,orRemark);
  }

  // 获取数据
  void _onLoading(gid,money,orRemark) async {
    // 此处不能获取上一个页面点击商品的id
    // http://xllm.szghrj.com:8082/app/goods/getGoodsById?gid=1424914810058878977
    // String url = "http://xllm.szghrj.com:8082/app/goods/getGoodsById?gid="+gid;
    // Response response = await Dio().get(url);
    // var x = json.decode(response.toString());
    SharedPreferences prefs = await SharedPreferences.getInstance();
    userId = prefs.getString("userId");
    var x = await HttpUtil().get("/app/goods/getGoodsById?gid="+gid);//得商品信息
    if(x['code']==200){
      obj = x['data'];
      yunfei = x['data']['yunfei'];
      if(names!=null && names!=""){
        price = money;
      }else{
        price = x['data']['gprice'];
      }
    }
    if(peisong == 1){
      allMoney = price*num + yunfei;
      if(adId!=null && adId!=""){
        var z = await HttpUtil().get("/app/address/getAddressById?id="+adId);//根究地址ID得地址信息
        if(z['code']==200){
          address = z['data'];
          addressCode = z['code'];
        }
      }else{
        var y = await HttpUtil().get("/app/address/getDefaultAddress?userId="+userId);//得用户默认收货地址
        addressCode = y['code'];
        if(y['code']==200){
          address = y['data'];
          adId = y['data']['id'];
        }
      }
    }else{
      allMoney = price*num;
      if(!hasDefaultZiti){
        if(adId!=null && adId!=""){
          var z = await HttpUtil().get("/app/zitidian/getZitidianById?zitiId="+adId);//根究地址ID得地址信息
          if(z['code']==200){
            zitiAddress = z['data'];
            hasDefaultZiti = true;
          }
        }
      }
    }
    if(orRemark!=null && orRemark!=""){
      _controller = TextEditingController(text: orRemark);
    }
    setState(() {});
  }

  // 显示订单状态
  Widget judgeAddress(addressCode){
    if(addressCode==200){
      return GestureDetector(child: Container(
          decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
          padding: EdgeInsets.all(10),
          child: Row(
            children: [
              Expanded(child:  Row(
                children: [
                  Icon(Icons.add_location),
                  Expanded(child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children:[
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text("${address['adName']}",style: TextStyle(fontSize: 18)),
                            Container(
                                // padding: EdgeInsets.fromLTRB(100, 0, 0, 0),
                                child: Text("${address['adPhone']}",style: TextStyle(fontSize: 14,color: Colors.black54))
                            )
                          ],),
                        Row(children: [Expanded(child:
                        Text("${address['addressDetail']}")
                        )],)
                      ]), ),
                ],)
              ),
              Align(alignment: Alignment.centerRight,child: Icon(Icons.navigate_next),)  ,
            ],
            // mainAxisAlignment: MainAxisAlignment.spaceBetween,
          )
      ),onTap: (){
        MyRoute.push(DizhiGuanli(type:1,gid:obj['gid'],num: num,names: names,params: params,money: price,allMoney: allMoney,orRemark: orRemark,));//跳地址管理页面
      },);
    }else if(addressCode==400){
      return GestureDetector(child: Container(
          decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
          padding: EdgeInsets.all(10),
          child: Row(
            children: [
              Row(children: [
                Icon(Icons.add_location),
                Center(child: Text("快捷添加收货地址")),
              ],),
              Icon(Icons.navigate_next),
            ],
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
          )
      ),onTap: (){
        MyRoute.push(AddDizhi(type:1,gid:obj['gid'],num: num,names: names,params: params,money: price,allMoney: allMoney,orRemark: orRemark,));//跳新增地址页面
        // MyRoute.push(AddDizhi(type:1,gid:obj['gid']));//跳新增地址页面
      },);
    }
    return GestureDetector(child: Container(
        decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
        padding: EdgeInsets.all(10),
        child: Row(
          children: [
            Row(children: [
              Icon(Icons.add_location),
              Center(child: Text("设置收货地址",style: TextStyle(fontSize: 16))),
            ],),
            Icon(Icons.navigate_next),
          ],
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
        )
    ),onTap: (){
      MyRoute.push(DizhiGuanli(type:1,gid:obj['gid'],num: num,names: names,params: params,money: price,allMoney: allMoney,orRemark: orRemark,));//跳地址管理页面
      // MyRoute.push(DizhiGuanli(type:1,gid:obj['gid']));//跳地址管理页面
    },);
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context , width: 464 , height: 820) ;
    return Scaffold(
      appBar: AppBar(
        title: Text("订单支付"),
        centerTitle: true,
      ),
      body: Column(
        children: <Widget>[
          new Expanded(
              child: Container(
                padding:EdgeInsets.all(10),
                child: ListView(
                  children: [
                    // 根据配送方式显示不同的地址
                   peisong==1? judgeAddress(addressCode) : showZitiAddress(),
                    // 没有默认收货地址的时候
                    // Container(
                    //     decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
                    //     padding: EdgeInsets.all(10),
                    //     child: Row(
                    //       children: [
                    //         Row(children: [
                    //           Icon(Icons.add_location),
                    //           Center(child: Text("快捷添加收货地址")),
                    //         ],),
                    //         Icon(Icons.navigate_next),
                    //       ],
                    //       mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    //     )
                    // ),
                    // 有默认收货地址的时候
                    // Container(
                    //     decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
                    //     padding: EdgeInsets.all(10),
                    //     child: Row(
                    //       children: [
                    //         Expanded(child:  Row(
                    //           children: [
                    //             Icon(Icons.add_location),
                    //             Expanded(child: Column(
                    //                 crossAxisAlignment: CrossAxisAlignment.start,
                    //                 children:[
                    //                   Row(
                    //                     mainAxisAlignment: MainAxisAlignment.start,
                    //                     children: [
                    //                       Text("${address['adName']}",style: TextStyle(fontSize: 18),),
                    //                       Text("${address['adPhone']}",style: TextStyle(fontSize: 14,color: Colors.black12))
                    //                     ],),
                    //                   Row(children: [Expanded(child:
                    //                   Text("${address['addressDetail']}")
                    //                   )],)
                    //                 ]), ),
                    //           ],)
                    //         ),
                    //         Align(alignment: Alignment.centerRight,child: Icon(Icons.navigate_next),)  ,
                    //       ],
                    //       // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    //     )
                    // ),
                    Container(
                      decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
                      padding: EdgeInsets.all(10),
                      margin: EdgeInsets.only(top: 10),
                      child: Column(
                      children: [
                        Row(children: [
                          Icon(Icons.card_giftcard),
                          Text("官方旗舰店")
                        ]),
                        Container(child: Row(children: [
                          // Image.network("https://www.itying.com/images/flutter/list2.jpg",fit: BoxFit.cover,width: 80,height: 80,),
                          Image.network(Config.getInstance().getHost()+obj['gimages'],fit: BoxFit.cover,width: 80,height: 80,),
                          Expanded(child: Column(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(children: [Text("${obj['gname']}")]),
                              Row(children: [names==null? Text(""):Expanded(child: Text(names)), ],),
                              Row(children: [
                                Text("￥${price}"),
                                Row(children: [
                                  GestureDetector(child: Container( child: Text("-"),
                                    decoration: BoxDecoration(
                                        border:Border.all(color: Colors.black , width: 1),
                                    color: Colors.white38,
                                    borderRadius: BorderRadius.all(Radius.circular(5))),
                                    padding: EdgeInsets.fromLTRB(8, 4, 8, 4),
                                    margin: EdgeInsets.only(right: 6),
                                  ),onTap: (){
                                    if(num > 1){
                                      setState(() {
                                        num--;
                                        if(peisong==1){
                                          allMoney = price*num+yunfei;
                                        }else{
                                          allMoney = price*num;
                                        }
                                      });
                                    }
                                  },
                                  ),
                                  Container(child: Text("${num}"),),
                                  GestureDetector(child: Container( child: Text("+"),
                                    decoration: BoxDecoration(
                                        border:Border.all(color: Colors.black , width: 1),
                                        borderRadius: BorderRadius.all(Radius.circular(5)),
                                      color: Colors.black12
                                    ),
                                    padding: EdgeInsets.fromLTRB(8, 4, 8, 4),
                                    margin: EdgeInsets.only(left: 6),
                                  ),
                                    onTap: (){
                                     setState(() {
                                       num++;
                                       if(peisong==1){
                                         allMoney = price*num+yunfei;
                                       }else{
                                         allMoney = price*num;
                                       }
                                     });
                                    },
                                  ),
                                ],)
                              ],
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              )
                            ],
                          )
                          )
                        ],
                        ),
                        height: 90,),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                          Text("运费"),
                          Text("￥${obj['yunfei']}")
                        ],),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text("订单备注："),
                            Expanded(child: TextField(
                              controller: _controller,
                              onChanged: (text){
                                orRemark = text;
                              },
                            ))
                          ],)
                      ],
                    ),
                    ),
                    Container(
                      decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
                      padding: EdgeInsets.all(10),
                      margin: EdgeInsets.only(top: 10),
                      child: Column(children: [
                      Row(children: [Text("选择配送方式")],) ,
                      Row(children: [
                        Checkbox(value: peisong==0, onChanged: (val) async {// 点击勾选
                          peisong=0;
                          var x = await HttpUtil().get("/app/order/selectUserDefaulZitidian?userId="+userId);//得用户默认自提点
                          if(x['code'] == 200){
                            zitiAddress = x['data'];
                            adId=x['data']['zitiId'];
                            hasDefaultZiti = true;
                          }
                          allMoney = price*num;
                          setState(() {});
                        }),
                        Text("自提")
                      ],),
                      Row(children: [
                        Checkbox(value: peisong==1, onChanged: (val) async {// 点击勾选
                          peisong=1;
                          var y = await HttpUtil().get("/app/address/getDefaultAddress?userId="+userId);//得用户默认收货地址
                          addressCode = y['code'];
                          if(y['code']==200){
                            address = y['data'];
                            adId = y['data']['id'];
                          }
                          allMoney = price*num+yunfei;
                          setState(() {});
                        }),
                        Text("送货")
                      ],)
                    ],),
                    ),
                    Container(
                      decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
                      padding: EdgeInsets.all(10),
                      margin: EdgeInsets.only(top: 10),
                      child: Column(children: [
                        Row(children: [Text("选择支付方式")],) ,
                        Row(children: [
                          Checkbox(value: true, onChanged: (val){// 点击勾选
                          }),
                          Text("积分")
                        ],),
                        Row(children: [
                          Checkbox(value: false, onChanged: (val){// 点击勾选
                          }),
                          Text("银行卡")
                        ],)
                      ],),
                    )
                  ],
                ),
                color: Colors.black12,
              )
          ),
          Row(
            children: <Widget>[
              Expanded(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Container(child: Column(children: [
                      Text("实付：￥${allMoney}",style: TextStyle(color: Colors.red, fontSize: 18)),
                      Text("共${num}件")
                    ],)
                    ),
                    GestureDetector(child:  Container(
                      alignment: Alignment.center,
                      child: new Text(
                        "立即付款",
                        style: TextStyle(color: Colors.white),
                      ),
                      width: ScreenUtil().setWidth(160),
                      height: ScreenUtil().setHeight(50),
                      color: Colors.red,
                    ),
                    onTap: () async {
                      //立即购买下订单，用户ID、商品ID、收货地址ID或自提点ID、订单备注、运费、订单价格、数量、配送类型、规格、规格下标
                      String addressId = adId;//收货地址ID或自提点ID
                      if(addressId==null || addressId==""){
                        Fluttertoast.showToast(
                            msg: "请选择收货地址"
                        );
                      }else{
                        if(peisong==0){
                          yunfei = 0;
                        }
                        var x = await HttpUtil().get("/app/order/submitOrder?gid="+"${obj['gid']}"+"&userId="+userId+"&orPeisongtype=${peisong}"+"&addressId="+addressId+"&orRemark=${orRemark}"+"&orYunfei=${yunfei}"+"&orPrice=${allMoney}"+"&orTotalnum=${num}"+"&names=${names}&params=${params}");
                        if(x['code']==200){
                          String unionid = x['msg'];
                          MyRoute.push(PayMima(unionid: unionid,userId: userId,money: allMoney,type:1));
                        }
                      }
                    },)
                  ],
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  showZitiAddress() {
    if(hasDefaultZiti){
      return GestureDetector(child: Container(
          decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
          padding: EdgeInsets.all(10),
          child: Row(
            children: [
              Expanded(child:  Row(
                children: [
                  Icon(Icons.add_location),
                  Expanded(child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children:[
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text("${zitiAddress['zitiName']}",style: TextStyle(fontSize: 18)),
                            Container(
                                // padding: EdgeInsets.fromLTRB(100, 0, 0, 0),
                                child: Text("${zitiAddress['phone']}",style: TextStyle(fontSize: 14,color: Colors.black54))
                            )
                          ],),
                        Row(children: [Expanded(child:
                        Text("${zitiAddress['zitiDetail']}")
                        )],)
                      ]), ),
                ],)
              ),
              Align(alignment: Alignment.centerRight,child: Icon(Icons.navigate_next),)  ,
            ],
            // mainAxisAlignment: MainAxisAlignment.spaceBetween,
          )
      ),onTap: (){
        MyRoute.push(ZitiListPage(type:1,peisong:peisong,gid:obj['gid'],num: num,names: names,params: params,money: price,allMoney: allMoney,orRemark: orRemark,));//跳地址管理页面
      },);
    }else{
      return GestureDetector(child: Container(
          decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
          padding: EdgeInsets.all(10),
          child: Row(
            children: [
              Row(children: [
                Icon(Icons.add_location),
                Center(child: Text("设置取货自提点",style: TextStyle(fontSize: 16))),
              ],),
              Icon(Icons.navigate_next),
            ],
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
          )
      ),onTap: (){
        MyRoute.push(ZitiListPage(type:1,peisong:peisong,gid:obj['gid'],num: num,names: names,params: params,money: price,allMoney: allMoney,orRemark: orRemark,));//跳自提点管理页面
      },);
      // return GestureDetector(child: Container(
      //     decoration: BoxDecoration(color: Colors.white,borderRadius: BorderRadius.circular(10)),
      //     padding: EdgeInsets.all(10),
      //     child: Row(
      //       children: [
      //         Expanded(child:  Row(
      //           children: [
      //             Icon(Icons.add_location),
      //             Expanded(child: Column(
      //                 crossAxisAlignment: CrossAxisAlignment.start,
      //                 children:[
      //                   Row(
      //                     mainAxisAlignment: MainAxisAlignment.start,
      //                     children: [
      //                       Text("请设置取货的自提点",style: TextStyle(fontSize: 18)),
      //                       Container(
      //                           padding: EdgeInsets.fromLTRB(100, 0, 0, 0),
      //                           child: Text("",style: TextStyle(fontSize: 14,color: Colors.black54))
      //                       )
      //                     ],),
      //                   Row(children: [Expanded(child:
      //                   Text("")
      //                   )],)
      //                 ]), ),
      //           ],)
      //         ),
      //         Align(alignment: Alignment.centerRight,child: Icon(Icons.navigate_next),)  ,
      //       ],
      //       // mainAxisAlignment: MainAxisAlignment.spaceBetween,
      //     )
      // ),onTap: (){
      //   MyRoute.push(ZitiListPage());//跳自提管理页面
      // },);
    }
  }

}